package com.apop.common.controller;

import com.apop.common.config.AppConfig;
import com.apop.common.exception.ErrorCode;
import com.apop.common.model.Result;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
 * 常用工具
 * @ClassName ToolController
 * @author Jiayi Zheng
 * @date 2021/11/10 15:35
 * @Description: 备用
 * @version V1.0
 */
@RestController
@RequestMapping("/tools")
@Slf4j
public class ToolController {

    @Autowired
    private Producer producer;

    @Autowired
    AppConfig configProperties;

    /**
     * 验证码接口
     * @param response
     * @param request
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/captcha")
    @ResponseBody
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.setContentType("image/jpeg");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        //生成文字验证码
        String text=producer.createText();
        //生成图片验证码
        BufferedImage image=producer.createImage(text);
        //保存验证码到session
        request.getSession().setAttribute("captcha", text);

        ServletOutputStream out=response.getOutputStream();
        ImageIO.write(image, "jpg", out);

        out.close();
    }

    /**
     * 文件上传接口-测试
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        String uploadPath = configProperties.getUploadPath();

        String msg = "";
        if (file.isEmpty()) {
            return Result.fail(new ErrorCode(500,"文件不能为空"));
        }

        String fileName = file.getOriginalFilename();
        File dis = new File(uploadPath);
        if(!dis.exists()){
            dis.mkdirs();
        }

        File dest = new File(uploadPath + fileName);
        try {
            file.transferTo(dest);
            msg = "文件上传成功"+uploadPath+fileName;
            return Result.success(msg);
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return Result.fail(new ErrorCode(500,"文件上传失败"));
    }
}
